package cn.edu.sdyu.ie.crs.service.impl;

import cn.edu.sdyu.ie.crs.domain.Classroom;
import cn.edu.sdyu.ie.crs.domain.ClassroomPlanning;
import cn.edu.sdyu.ie.crs.repository.ClassroomPlanningRepository;
import cn.edu.sdyu.ie.crs.repository.ClassroomRepository;
import cn.edu.sdyu.ie.crs.service.ClassroomPlanningService;
import cn.edu.sdyu.ie.crs.service.ClassroomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class ClassroomPlanningServiceImpl implements ClassroomPlanningService {

    @Autowired
    private ClassroomPlanningRepository classroomPlanningRepository;

    @Override
    public List<ClassroomPlanning> findAll() {
        return classroomPlanningRepository.findAll();
    }

    @Override
    public Page<ClassroomPlanning> findByPage(Integer page, Integer pageSize) {
        Pageable pageable = PageRequest.of(page, pageSize, Sort.by(Sort.Direction.DESC,"id"));
        return classroomPlanningRepository.findAll(pageable);
    }

    @Override
    public ClassroomPlanning findClassroomPlanningById(Integer id) {
        Optional<ClassroomPlanning> optional = classroomPlanningRepository.findById(id);
        if(optional.isPresent()) {
            return optional.get();
        } else {
            log.warn("指定教室计划信息[ID:{}]不存在", id);
            return null;
        }

        // return classroomPlanningRepository.findById(id).orElse(null);
    }

    @Override
    public void saveClassroomPlanning(ClassroomPlanning classroomPlanning) {
        if(classroomPlanning.getId() == null) {
            classroomPlanning.setCreateTime(new Date());
        }
        classroomPlanningRepository.save(classroomPlanning);
    }

    @Override
    public void deleteClassroomPlanningById(Integer id) {
        classroomPlanningRepository.deleteById(id);
    }

    @Override
    public List<ClassroomPlanning> findClassroomPlanningsByClassroomId(Integer classroomId) {
        return classroomPlanningRepository.findClassroomPlanningsByClassroomId(classroomId);
    }
}
